package com.cyx.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyx.common.core.constants.CacheConstants;
import com.cyx.common.core.constants.Constants;
import com.cyx.common.core.enums.ExamListType;
import com.cyx.common.core.enums.ResultCode;
import com.cyx.common.redis.service.RedisService;
import com.cyx.common.security.exception.ServiceException;
import com.cyx.friend.domain.exam.Exam;
import com.cyx.friend.domain.exam.ExamQuestion;
import com.cyx.friend.domain.exam.dto.ExamQueryDTO;
import com.cyx.friend.domain.exam.vo.ExamVO;
import com.cyx.friend.domain.user.UserExam;
import com.cyx.friend.mapper.exam.ExamMapper;
import com.cyx.friend.mapper.exam.ExamQuestionMapper;
import com.cyx.friend.mapper.user.UserExamMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ExamCacheManager {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private RedisService redisService;
    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    public Long getListSize(Integer examListType, Long userId) {
        String examListKey = getExamListKey(examListType, userId);
        return redisService.getListSize(examListKey);
    }

    public Long getExamQuestionListSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);
    }

    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {
        // 获取下标
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1;
        // redis中存储的竞赛列表的key
        String examListKey = getExamListKey(examQueryDTO.getType(), userId);
        // 从redis中获取竞赛列表的所有竞赛id的list
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
       // 根据竞赛id的list从redis中获取竞赛列表
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        // 如果列表为空
        if(CollectionUtil.isEmpty(examVOList)) {
            // 从数据库中获取
            examVOList = getExamListByDB(examQueryDTO, userId);
            // 刷新缓存
            refreshCache(examQueryDTO, userId);
        }
        return examVOList;
    }

    public List<Long> getAllUserExamList(Long id) {
        // 先尝试从缓存中获取
        String userExamKey = CacheConstants.USER_EXAM_LIST + id;
        List<Long> userExamIdList = redisService.getCacheListByRange(userExamKey,0,  - 1, Long.class);
        // 缓存中有，直接返回
        if(CollectionUtil.isNotEmpty(userExamIdList)) {
            return userExamIdList;
        }
        // 缓存中没有，去数据库中拿
        List<UserExam> userExamList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>().eq(UserExam::getUserId, id));

        // 数据库中也没有，返回null
        if(CollectionUtil.isEmpty(userExamList)) return null;
        // 最后返回的是竞赛id列表，需要用stream流处理一下
        return userExamList.stream().map(UserExam::getExamId).toList();
    }

    public Long addUserExamCache(Long userId, Long examId) {
        String userExamListKey = getUserExamListKey(userId);
        return redisService.leftPushForList(userExamListKey, examId);
    }

    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getExamQuestionListKey(examId), 0, Long.class);
    }

    public Long preQuestion(Long examId, Long questionId) {
        long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        if(index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId), index - 1, Long.class);
    }

    public Long nextQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        long lastIndex = getExamQuestionListSize(examId) - 1;
        if(index == lastIndex) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId), index + 1, Long.class);
    }

    public void refreshCache(ExamQueryDTO examQueryDTO, Long userId) {
        List<Exam> examList = new ArrayList<>();
        Integer examListType = examQueryDTO.getType();
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(examQueryDTO, userId);
            examList = BeanUtil.copyToList(examVOList, Exam.class);
        }
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        // 遍历竞赛列表，将竞赛id和竞赛映射起来存储到map中
        // 并将id存储到list中
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        // 这里为什么要用multiSet（批量存储）
        // 因为从数据库中获取的竞赛列表中的竞赛可能不止一个，使用批量存储提高效率
        redisService.multiSet(examMap);  //刷新详情缓存
        // 为了防止重复数据，先清空redis中存储竞赛id的list
        redisService.deleteObject(getExamListKey(examListType, userId));
        // 再使用尾插法重新存储数据
        redisService.rightPushAll(getExamListKey(examListType, userId), examIdList);      //刷新列表缓存
    }

    public void refreshExamQuestionCache(Long examId) {
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        if(CollectionUtil.isEmpty(examQuestionList)) {
            return;
        }
        List<Long> examQuestionIdList = examQuestionList.stream().map(ExamQuestion::getQuestionId).toList();
        redisService.rightPushAll(getExamQuestionListKey(examId), examQuestionIdList);
    }

    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO, Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        if(userId == null) {
            return examMapper.selectExamList(examQueryDTO);
        } else {
            return userExamMapper.selectUserExamList(examQueryDTO, userId);
        }
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        // 从redis中批量获取数据
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        // 可能会出现有问题的数据，那么就说明缓存该刷新了，那么将这些有问题的数据删除
        CollUtil.removeNull(examVOList);
        // 判断数据中是否存在有问题的数据
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    private String getExamListKey(Integer examListType, Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            return CacheConstants.USER_EXAM_LIST + userId;
        }
    }

    private String getUserExamListKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }
}
